<template>
  <div class="btn-item" @click="toggleInput">
    <svg-icon name="icon-message" color="#fff"></svg-icon>
    <div class="dialog" :class="{ act: showDialog }" @click.stop>
      <input
        v-if="showDialog"
        type="text"
        v-model="message"
        placeholder="输入消息..."
        @keyup.enter="sendMessage"
        class="message-input"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const showDialog = ref(false)
const message = ref('')

function toggleInput() {
  showDialog.value = !showDialog.value
  if (showDialog.value) {
    setTimeout(() => {
      document.body.addEventListener('click', closeDialog, { once: true });
    }, 0);
  }
}

function closeDialog(event) {
  if (event.target.closest('.btn-item')) return
  showDialog.value = false;
}

function sendMessage() {
  if (message.value.trim()) {
    emit('send-message', message.value)
    message.value = '' // 发送后清空输入框
    showDialog.value = false
  }
}

const emit = defineEmits(['send-message']);
</script>

<style scoped lang="scss">
.btn-item {
  width: 50px;
  height: 50px;
  background-color: rgba(255, 255, 255, 0.25);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 26px;
  position: relative;
  cursor: pointer;
  &:hover {
    background-color: rgba(255, 255, 255, 0.2);
  }
}

.dialog {
  width: 300px;
  background: #222222;
  position: absolute;
  bottom: 70px;
  left: 0;
  border-radius: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  overflow-y: auto;
  overflow-x: hidden;
  height: 0;
  transition: height 0.3s ease;
  cursor: pointer;

  &.act {
    height: auto; /* 弹出时显示输入框 */
  }

  .message-input {
    width: 100%;
    padding: 8px;
    background-color: #333;
    border: none;
    color: white;
    border-radius: 5px;
    margin: 10px;
    font-size: 14px;
    outline: none;
  }
}
</style>
